package com.czy.ekp.controller;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSONObject;
import com.czy.ekp.datasource.DynamicDataSourceContextHolder;
import com.czy.ekp.template.TemplateService;
import com.czy.ekp.util.FileUtils;
import com.czy.ekp.util.ResultMap;
import com.wbs.rest.config.SqlRestContext;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Controller
public class IndexController {


    @Autowired
    SqlRestContext sqlRestContext;


    @RequestMapping({"", "/", "/index"})
    public String index(){
        return "redirect:/html/index.html";
    }

    @PostMapping("/resetMapping")
    @ResponseBody
    public ResultMap resetMapping(){
        sqlRestContext.reloadMapping();
        return ResultMap.success("Sql映射加载完毕");
    }


    @PostMapping("/resetDatabase")
    @ResponseBody
    public ResultMap resetDatabase(@RequestBody Map<String, String> map){

        DynamicDataSourceContextHolder.setDataSource(map.get("a"), map.get("b"), map.get("c"), map.get("d"));

        return ResultMap.success("数据源更换完毕");
    }

    @PostMapping("/resetDefault")
    @ResponseBody
    public ResultMap resetDefault(){

        DynamicDataSourceContextHolder.setDataSource(DynamicDataSourceContextHolder.defaultDataSource);

        return ResultMap.success("数据源更换完毕");
    }

    @PostMapping("/file/upload")
    @ResponseBody
    public ResultMap upload(MultipartFile file){
        return FileUtils.fileUpload("/upload", "/file/download?file=", file);
    }

    @GetMapping("/file/download")
    public void download(String file, HttpServletResponse response){
        try{
            FileUtils.fileDownload("/upload", file, response.getOutputStream());
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
